import dayjs from 'dayjs'
import { Video } from '../types/chapter'

// 格式化日期
export const formatDate = (date: string) => {
    return dayjs(date).format('YYYY-MM-DD HH:mm')
}

export const formatDateShort = (date: string) => {
    return dayjs(date).format('YYYY-MM-DD')
}

export const formatDateTime = (date: string) => {
    return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

// 格式化时间
export const formatTime = (date: Date | string | number) => {
    console.log('更新时间',date)
    const parsedDate = new Date(date); // 统一转换为 Date 对象
    const diff = Date.now() - parsedDate.getTime();
    const days = Math.floor(diff / 86400000);
    return `${days}天前`;
  }

  /**
 * 使用dayjs解析日期字符串为Date对象
 * @param dateString 日期字符串
 * @returns Date对象
 */
export const parseDateTime = (dateString: string | number | dayjs.Dayjs | Date): Date => {
    return dayjs(dateString).toDate()
  }
  

  /**
   * 实现秒转分
   */
  export const secondToMinute = (seconds: number): string => {
    const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  // 补零显示（如 2 分钟 5 秒 → "02:05"）
  return `${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`;
  }
 

  /**
   * 分钟转时分秒
   * @param milliseconds 
   * @returns 
   */
export const formatDuration = (milliseconds: number) => {
  // 处理负值和边界情况
  if (milliseconds <= 0) return '00:00:00'
  
  const totalSeconds = Math.floor(milliseconds / 1000)
  const hours = Math.floor(totalSeconds / 3600)
  const minutes = Math.floor((totalSeconds % 3600) / 60)
  const seconds = totalSeconds % 60

  // 补零格式化
  const pad = (num: number) => num.toString().padStart(2, '0')
  
  return `${pad(hours)}时${pad(minutes)}分${pad(seconds)}秒`
}

// 时间解析函数（按本地时区处理）
export const parseExamTime = (timeStr: string) => {
  // 将格式转换为 "YYYY-MM-DDTHH:mm:ss" 按本地时区解析
  const isoString = timeStr.replace(' ', 'T')
  const timestamp = Date.parse(isoString)
  
  if (isNaN(timestamp)) {
    console.error('Invalid time format:', timeStr)
    return 0
  }
  return timestamp
}

/**
 * 格式化视频时长格式
 */
 export const formatDurationVideo = (seconds: number) => {
 // 处理浮点数并取整
 const totalSeconds = Math.round(seconds)
  
 // 计算时间分量
 const hours = Math.floor(totalSeconds / 3600)
 const minutes = Math.floor((totalSeconds % 3600) / 60)
 const secs = totalSeconds % 60

 // 构建格式组件
 const timeComponents = []
 if (hours > 0) {
   timeComponents.push(hours.toString().padStart(2, '0'))
 }
 timeComponents.push(
   minutes.toString().padStart(2, '0'),
   secs.toString().padStart(2, '0')
 )

 // 智能格式选择
 return timeComponents.length > 2 
   ? `${timeComponents[0]}:${timeComponents[1]}:${timeComponents[2]}` 
   : `${timeComponents[0]}:${timeComponents[1]}`
}


// 章节总时长计算方法
export const chapterDurationTotal = (videos: Video[]) => {
  // 使用更精确的累加方式避免浮点误差
  const total = videos.reduce((sum, video) => {
    // 四舍五入到整数秒
    return sum + Math.round(video.duration || 0)
  }, 0)
  
  return formatDurationVideo(total)
}


// 时间格式化
export const formatTime3 = (timestamp: number) => {
  return dayjs(timestamp).format('YYYY-MM-DD HH:mm')
}

// 时长格式化
export const formatDuration3 = (seconds: number) => {
  const h = Math.floor(seconds / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  const s = seconds % 60
  return [h, m, s].map(v => v.toString().padStart(2, '0')).join(':')
}